/**
 * 文件名称: SessionFilterSupport.java
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2013-8-9
 */
package com.pshare.framework.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.pshare.constant.SeaxConstants;
import com.pshare.util.CookieUtil;
import com.pshare.util.SysPropertyUtils;

/**
 * 会话过滤器
 */
public class SessionFilterSupport implements Filter {

	private static final String DOMAIN = SysPropertyUtils.getProperty("Domain");
	public static final int COOKIE_MAX_AGE = -1;
	public static final String COOKIE_PATH = "/";


	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	/**
	 * <p>
	 * 不管用户是否登录，都会返回一个用户唯一会话设置在HttpServletResponse响应Cookie中。
	 * 每次客户端请求都会发送Cookie来获取用户是否已经登录等验证操作。
	 * </p>
	 * 
	 * @param request
	 * @param response
	 */
	protected void setCookie(HttpServletRequest request, HttpServletResponse response) {
		String sessionId = CookieUtil.getToken(request);
		if (StringUtils.isBlank(sessionId)) {
			CookieUtil.setCookie(response, DOMAIN, request.getContextPath() + COOKIE_PATH, SeaxConstants.COOKIE_KEY, sessionId,
					COOKIE_MAX_AGE);
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		if (!(request instanceof HttpServletRequest)) {
			chain.doFilter(request, response);
			return;
		}

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		setCookie(httpRequest, httpResponse);

		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		
	}
}
